package cn.nawang.ebeim.client.util;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.nawang.ebeim.client.bean.ClientConfiguration;

import org.apache.zookeeper.ZooKeeper;

/**
 * @ClassName: ZookeeperUtil
 * @Description: TODO
 * @author 许炜毅
 * @date 2015年8月25日 下午3:19:00
 * @version v1.0
 */
public class ZookeeperUtil implements Watcher {
  private static final Logger LOG = LoggerFactory.getLogger(ZookeeperUtil.class);
  private static String hosts;
  protected static ZooKeeper zooKeeper;
  protected static CountDownLatch countDownLatch = new CountDownLatch(1);

  public static void connect(String hosts) throws IOException, InterruptedException {
    LOG.info("ZookeeperHost"+hosts);
    ZookeeperUtil.hosts = hosts;
    if(zooKeeper==null)
    zooKeeper = new ZooKeeper(hosts, ClientConfiguration.getSessionTime(), new ZookeeperUtil());
    countDownLatch.await();
  }

  public void process(WatchedEvent event) {
    if (event.getState() == KeeperState.SyncConnected) {
      countDownLatch.countDown();
    }
  }

  public static void close() throws InterruptedException {
    zooKeeper.close();
  }

  public static boolean exists(String nodePath) throws KeeperException, InterruptedException {
    if (zooKeeper.exists(nodePath, false) != null) {
      return true;
    }
    return false;
  }

  // 使用主机名作为znode名称
  public static void create(String path, byte[] data) throws KeeperException, InterruptedException {
    zooKeeper.create(path, data, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
  }

  public static void create(String path) throws KeeperException, InterruptedException {
    zooKeeper.create(path, "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
  }

  public static List<String> getChildNodeList(String path)//  /ebeim/pc1   /ebeim/pc2
      throws KeeperException, InterruptedException {
    List<String> list = null;
    try {
      list = zooKeeper.getChildren(path, false);
      if (list.isEmpty()) {
        LOG.debug(path + " 中没有节点");
      } else {
        LOG.debug(path + " 中存在节点");
      }
    } catch (KeeperException.NoNodeException e) {
            //throw e;
              LOG.debug(e.toString());
   }catch (KeeperException.SessionExpiredException e) {
              LOG.debug(e.toString());
              try {
                 zooKeeper.close();
                  zooKeeper = new ZooKeeper(hosts, ClientConfiguration.getSessionTime(), new ZookeeperUtil());
                  list = zooKeeper.getChildren(path, false);
              } catch (IOException e1) {
                  e1.printStackTrace();
              } 
   }
    return list;
  }

  public static String getData(String path) throws KeeperException, InterruptedException {//ip:port
    return new String(zooKeeper.getData(path, false, null));
  }

  public static String getLocalHostIp() {
    try {
      InetAddress ia = InetAddress.getLocalHost();
      if(null == ia){
        return null;
      }
      return ia.getHostAddress();
    } catch (UnknownHostException e) {
      LOG.debug("unknown host!");
    }
    return null;
  }

  public static String getLocalHostName() {
    try {
      InetAddress ia = InetAddress.getLocalHost();
      if(null == ia){
        return null;
      }
      return ia.getHostName();
    } catch (UnknownHostException e) {
      LOG.debug("unknown host!");
    }
    return null;
  }

}
